package com.sise.thread.lab01.lab02;

class ThreadTrain2 implements Runnable{
    private int trainCount=100;
    public Object obj=new Object();

    public boolean flag=true;
    //局部变量不会受到线程安全问题的影响
    @Override
    public void run() {
        if(flag){
            while (trainCount>0) {
                try {
                    Thread.sleep(50);
                } catch (Exception e) {
                }
                //使用了同步代码块，里面用的是this锁
                synchronized (obj) {
                    if (trainCount > 0) {
                        System.out.println(Thread.currentThread().getName() + ":开始售出第" + (100 - trainCount + 1) + "" + "张票");
                    }
                    trainCount--;
                }
            }
        }else{
            while (trainCount>0) {
                try {
                    sale();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private synchronized void sale() throws InterruptedException {
        //同步代码块 ---走到这个位置的时候，可能会有多个线程进行访问，谁先拿到锁谁就先进行购票
            if (trainCount > 0) {
                Thread.sleep(40);
                System.out.println(Thread.currentThread().getName() + ":开始售出第" + (100 - trainCount + 1) + "" + "张票");
            }
            trainCount--;
        }
    }


//模拟火车站抢票
public class ThreadMain02 {
    public static void main(String[] args) throws InterruptedException {
        //为了模拟有两个窗口在抢票
        ThreadTrain2 threadTrain2=new ThreadTrain2();
        Thread t1= new Thread(threadTrain2,"窗口1");
        Thread t2= new Thread(threadTrain2,"窗口2");
        t1.start();
        Thread.sleep(40);
        threadTrain2.flag=false;
        t2.start();
    }
}
